<template>
  <a-modal
    :title="title"
    v-model="show"
    :maskClosable="false"
    :width="1050"
    placement="right"
    :closable="true"
    @cancel="onClose"
    :footer="null"
    :visiable="instructionRuleOperationVisiable"
  >
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="指令类型标识"
                       v-bind="formItemLayout">
            <a-input v-decorator="['instructionType']" placeholder="系统自动生成" :disabled="true"/>
          </a-form-item>
          <a-form-item label="id"
                       v-bind="formItemLayout" style="display: none">
            <a-input v-decorator="['id']"/>
          </a-form-item>
          <a-form-item style="display: none">
            <a-input type="hidden" name="auditStatus" v-decorator="['auditStatus']"/>
          </a-form-item>
          <a-form-item style="display: none">
            <a-input type="hidden" name="oprId" v-decorator="['oprId']"/>
          </a-form-item>
          <a-form-item style="display: none">
            <a-input type="hidden" name="oprStatus" v-decorator="['oprStatus']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="指令描述"
                       v-bind="formItemLayout">
            <a-input v-decorator="['settleRuleDesc',{rules: [{ required: true, message: '必填' }]}]"
                     :disabled="this.isUpd"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24" v-show="this.isStop == true">
          <a-form-item label="停用原因"
                       v-bind="formItemLayout">
            <a-input v-decorator="['stopReason',{rules: [{ required: this.isStop, message: '必填' }]}]"/>
          </a-form-item>
        </a-col>

        <a-col :md="12" :sm="24" v-show="this.isCancel == true">
          <a-form-item label="注销原因"
                       v-bind="formItemLayout">
            <a-input v-decorator="['cancelReason',{rules: [{ required: this.isCancel, message: '必填' }]}]"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <div>
          <div class="operator" v-show="this.title == '新增指令规则' || this.title == '修改指令规则'">
            <a-button ghost type="primary" @click="addInstructionRule">新增</a-button>
          </div>
          <!-- 表格区域 -->
          <a-table ref="TableInfo"
                   :columns="columns"
                   :rowKey="record => record.id"
                   :dataSource="dataSource"
                   :pagination="pagination"
                   :loading="loading"
                   :scroll="{ x: 1000 }"
                   @change="handleTableChange">
            <template slot="email" slot-scope="text, record">
              <a-popover placement="topLeft">
                <template slot="content">
                  <div>{{text}}</div>
                </template>
                <p style="width: 150px;margin-bottom: 0">{{text}}</p>
              </a-popover>
            </template>
            <template slot="ruleOperation" slot-scope="text, record, index">
              <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5" v-if="optFlagTmp !== 'view' "
                      @click="editInstructionRule(record)" title="修改"></a-icon>&nbsp;
              <a-icon type="delete" theme="twoTone" twoToneColor="#42b983" v-if="optFlagTmp !== 'view'"
                      @click="delInstructionRule(record,index)" title="删除"></a-icon>
            </template>

          </a-table>
        </div>
      </a-row>
    </a-form>
    <div class="firstColAdd" v-show="this.title !== '详情'">
      <a-button @click="onClose" type="primary">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>

    <div>
      <!-- 新增或修改 -->
      <instruction-rule-edit
        ref="instructionRuleEdit"
        @close="handleInstructionRuleEditClose"
        @success="handleInstructionRuleEditSuccess"
        :instructionRuleEditVisiable="instructionRuleEdit.visiable">
      </instruction-rule-edit>
    </div>
  </a-modal>
</template>
<script>
  const formItemLayout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16}
  }

  import InstructionRuleEdit from "./InstructionRuleEdit";

  export default {
    name: 'InstructionRuleOperation',
    components: {InstructionRuleEdit},
    props: {
      instructionRuleOperationVisiable: {
        default: false
      },
      instId: '',
    },
    data() {
      return {
        title: '新增指令规则',
        isStop: false,
        isCancel: false,
        isUpd: false,
        loading: false,
        formItemLayout,
        form: this.$form.createForm(this),
        validateStatus: '',
        instructionRuleEdit: {
          visiable: false
        },
        info: {
          infoName: '',
          remark: '',
          menuId: ''
        },
        optFlagTmp: 'add',
        dataSource: [],
        sortedInfo: null,
        paginationInfo: null,
        // selectedRowKeys: [],
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },

      }
    },
    computed: {
      show: {
        get: function () {
          return this.instructionRuleOperationVisiable
        },
        set: function () {
        }
      },
      columns() {
        let {sortedInfo} = this
        sortedInfo = sortedInfo || {}
        let {filteredInfo} = this
        filteredInfo = filteredInfo || {}
        return [{
          title: '清算规则标识',
          dataIndex: 'settleRuleId',
          scopedSlots: {customRender: 'settleRuleId'},
        }, {
          title: '清算规则序号',
          dataIndex: 'settleRuleIndex',
          scopedSlots: {customRender: 'settleRuleIndex'},
        }, {
          title: '业务产品类型',
          dataIndex: 'bizProdType',
          customRender: (text, row, index) => {
            switch (text) {
              case '01':
                return '银联CUPS受理侧'
              case '02':
                return '微信支付'
              case '03':
                return '支付宝支付'
              case '04':
                return '分期'
              case '05':
                return '积分'
              case '06':
                return '银联小微二维码'
              case '07':
                return '网联受理侧'
              case '08':
                return '本行渠道业务'
              case '11':
                return '银联助农业务'
              case '21':
                return '银联线上支付'
              case '22':
                return '银联无卡快捷受理侧'
              case '23':
                return '银联全渠道-代付'
              case '24':
                return '银联全渠道-无跳转'
              case '25':
                return '银联全渠道-代收'
              case '26':
                return '深圳银联业务'
              case '27':
                return '厦门银联业务'
              case '31':
                return '银联二维码'
              case '90':
                return '银联CUPS发卡侧'
              case '91':
                return '网联发卡侧'
              case '92':
                return '银联无卡快捷发卡侧'
              case '40':
                return '提现'
              case '41':
                return '商户入账失败挂账'
              case '42':
                return '风险资金挂账'
              case '43':
                return '商户风险资金入账失败挂账'
              case '44':
                return '代理商分润'
              case '45':
                return '营销'
              case '46':
                return 'D0补入账'
              case '47':
                return '虚拟账户业务'
              case '48':
                return '人行大小额'
              case '49':
                return '超级网银'
              default:
                return text
            }
          }
        }, {
          title: '清算资金类型',
          dataIndex: 'settleFundType',
          customRender: (text, row, index) => {
            switch (text) {
              case '00':
                return '交易金额'
              case '01':
                return '商户手续费'
              case '02':
                return '商户入账净额'
              case '03':
                return '商户优惠手续费'
              case '04':
                return '代理商手续费'
              case '10':
                return '银联转接清算费'
              case '11':
                return '银联交换费(卡组织手续费）'
              case '12':
                return '品牌服务费'
              case '13':
                return '差错费用'
              case '14':
                return '支付通道手续费'
              case '20':
                return '收单手续费'
              case '21':
                return '发卡手续费'
              case '22':
                return '分行补贴手续费'
              case '30':
                return '跨行持卡人手续费'
              case '31':
                return '持卡人异地手续费'
              default:
                return text
            }
          }
        }, {
          title: '资金清算方式',
          dataIndex: 'settleMethod',
          customRender: (text, row, index) => {
            switch (text) {
              case 'SUM':
                return '聚合清算'
              case 'DIS':
                return '独立清算'
              default:
                return text
            }
          },
        }, {
          title: '计算规则',
          dataIndex: 'calcRule',
          scopedSlots: {customRender: 'calcRule'},
        }, {
          title: '操作',
          dataIndex: 'ruleOperation',
          fixed: 'right',
          width: 100,
          scopedSlots: {customRender: 'ruleOperation'}
        }]
      }
    },
    mounted() {

    },

    methods: {

      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },

      addInstructionRule() {
        let settleRuleDesc = this.form.getFieldsValue(['settleRuleDesc'])
        var record = {};
        record.instId = this.instId;
        let settleRuleIndexTmp = 1
        if (this.dataSource.length != 0) {
          let num = this.dataSource[this.dataSource.length - 1].settleRuleIndex
          settleRuleIndexTmp = parseInt(num) + 1
        }
        console.log(settleRuleIndexTmp,'========')
        var settleRuleIndex = this.dataSource.length <= 0 ? 1 : settleRuleIndexTmp;
        record.settleRuleIndex = settleRuleIndex
        record.id = settleRuleIndex

        record.optFlag = 'add'
        console.log(record)
        if (settleRuleDesc.settleRuleDesc) {
          this.instructionRuleEdit.visiable = true
          this.$refs.instructionRuleEdit.setInstructionRuleFormRecordValues(record);
        } else {
          this.$message.warning("请先填写指令描述！");
        }
      },


      editInstructionRule(record) {
        let settleRuleDesc = this.form.getFieldsValue(['settleRuleDesc'])
        record.optFlag = 'upd'
        if (settleRuleDesc.settleRuleDesc) {
          this.instructionRuleEdit.visiable = true
          this.$refs.instructionRuleEdit.setInstructionRuleFormRecordValues(record);
        } else {
          this.$message.warning("请先填写指令描述！");
        }

      },

      delInstructionRule(record, index) {
        this.dataSource.splice(index, 1);
      },

      handleInstructionRuleEditClose() {
        this.instructionRuleEdit.visiable = false
      },
      handleInstructionRuleEditSuccess(data) {
        this.instructionRuleEdit.visiable = false
        console.log(data)
        if ("add" == data.optFlag) {
          this.dataSource.push(data);
          if (this.paginationInfo && this.paginationInfo.pageSize) {
            this.paginationInfo.pageSize = this.paginationInfo.pageSize + 1;
          }
        } else {
          /* 通过 this.dataSource.forEach 遍历赋值后并不会通过数据双向绑定更新dataSource里的内容 */
          for (var i = 0; i < this.dataSource.length; i++) {
            if (data.settleRuleIndex == this.dataSource[i].settleRuleIndex) {
              this.dataSource[i].id = data.id;
              this.dataSource[i].settleRuleId = data.settleRuleId;
              this.dataSource[i].settleRuleIndex = data.settleRuleIndex;
              this.dataSource[i].bizProdType = data.bizProdType;
              this.dataSource[i].settleFundType = data.settleFundType;
              this.dataSource[i].settleMethod = data.settleMethod;
              this.dataSource[i].calcRule = data.calcRule;
            }
          }
        }
      },

      reset() {
        this.loading = false
        this.isCancel = false
        this.isUpd = false
        this.isStop = false
        this.title = '新增指令规则'
        this.dataSource = []
        this.optFlagTmp = 'add'
        this.form.resetFields()
      },
      onClose() {
        this.reset()
        this.$emit('close')
      },
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (!err) {
            if (this.dataSource.length == 0) {
              return this.$message.warning('请点击 [ 新增 ]按钮，增加指令规则信息！')
            }

            this.setInfoFields()
            this.loading = true
            this.dataSource.forEach((data) => {
              data.instId = this.instId
              data.instructionType = this.info.instructionType
              data.settleRuleDesc = this.info.settleRuleDesc
              data.auditStatus = this.info.auditStatus
              data.oprId = this.info.oprId
              data.oprStatus = this.info.oprStatus
              data.stopReason = this.info.stopReason
              data.cancelReason = this.info.cancelReason
            })
            let optFlag = this.optFlagTmp

            const params = {
              instructionRuleList: this.dataSource,
              optFlag: optFlag,
            }

            console.log(params)
            this.$postJson('/admin/csmc/cInstructionRule', params).then((r) => {
              this.reset()
              this.$emit('success')
            }).catch(() => {
              this.loading = false
            })

          }
        })
      },

      setInfoFields() {
        let values = this.form.getFieldsValue(['id', 'instructionType', 'settleRuleDesc', 'stopReason',
          'cancelReason', 'auditStatus', 'oprId', 'oprStatus'])
        if (typeof values !== 'undefined') {
          Object.keys(values).forEach(_key => {
            this.info[_key] = values[_key]
          })
        }
      },

      setInstructionRuleFormValues({...info}) {
        let fields = ['id', 'instructionType', 'settleRuleDesc', 'auditStatus', 'oprId', 'oprStatus']
        this.optFlagTmp = info.operation
        if (info.operation == 'stop') {
          this.isStop = true
          this.isUpd = true
          this.title = '停用指令规则'
        } else if (info.operation == 'use') {
          this.isUpd = true
          this.title = '启用指令规则'
        } else if (info.operation == 'cancel') {
          this.isCancel = true
          this.isUpd = true
          this.title = '注销指令规则'
        } else if (info.operation == 'view') {
          this.isUpd = true
          this.title = '详情'
        } else if (info.operation == 'upd') {
          this.title = '修改指令规则'
        }
        Object.keys(info).forEach((key) => {
          if (fields.indexOf(key) !== -1) {
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = info[key]
            this.form.setFieldsValue(obj)
          }
        })

        this.fetch();
      },

      handleTableChange(pagination, filters, sorter) {
        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        // 重置列过滤器规则
        this.filteredInfo = null
        // 重置列排序规则
        this.sortedInfo = sorter

        // this.reconSceneInfo.visiable = false
        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      fetch(params = {}) {
        this.loading = true
        if (this.paginationInfo) {
          // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
          this.$refs.TableInfo.pagination.current = this.paginationInfo.current
          this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
          params.pageSize = this.paginationInfo.pageSize
          params.pageNum = this.paginationInfo.current
        } else {
          // 如果分页信息为空，则设置为默认值
          params.pageSize = this.pagination.defaultPageSize
          params.pageNum = this.pagination.defaultCurrent
        }
        params.id = this.form.getFieldValue("id");
        params.instId = this.instId;
        params.instructionType = this.form.getFieldValue("instructionType");

        if ((params.id && params.id != null && params.id.toString() != "") &&
          (this.optFlagTmp && this.optFlagTmp != null && this.optFlagTmp.toString() != "")) {
          params.optFlag = this.optFlagTmp;

          this.$get('/admin/csmc/cInstructionRule/cInstructionRuleDialog', {
            ...params
          }).then((r) => {
            let data = r.data
            this.loading = false
            this.dataSource = r.data.rows
            const pagination = {...this.pagination}
            pagination.total = data.total
            this.pagination = pagination
          })
        } else {
          this.loading = false;
        }
      }

    }

  }
</script>
<style>
  .firstColAdd {
    text-align: right;
    margin-top: 8px;
    margin-right: 28px
  }
</style>




